iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 17
1
自我挑戰組

30天學python系列 第 17

[Day17] Python 語言進階 - 1

  • 分享至 

  • xImage
  •  

接下來是 100 天當中的第二部分 Python 語言進階。我也會分成好幾天做這階段的筆記。

1.數據結構和算法

  • 算法:解決問題的方法和步驟

  • 評價算法的好壞:漸近時間複雜度和漸近空間複雜度。

  • 漸近時間複雜度的大 O (Big-o) 標記:

    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116Phsc6O4OoR.png - 恆定時間複雜度 - 布隆過濾器 (Bloom Filter) / 雜湊表 (Hash table) 存儲
    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116tyj7kRYgYg.png - 對數時間複雜度 - 二分搜尋 (Binary Search)
    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116Z6UAkyyJIj.png - 線性時間複雜度 - 循序搜尋 (Sequential Search) / 桶排序 (Bucket Sort)
    • https://ithelp.ithome.com.tw/upload/images/20190928/201211169IIdqWsYmq.png - 對數線性時間複雜度 - 高級排序算法(合併排序 (Merge sort)、快速排序 (Quick sort))
    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116clXGCYgb4Y.png - 平方時間複雜度 - 簡單排序算法(選擇排序 (Selection sort)、插入排序(Insertion sort)、氣泡排序 (Bubble sort))
    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116zYYom2lmeP.png - 立方時間複雜度 - Floyd 算法 / 矩陣乘法運算
    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116ZyRNdqm5kX.png - 指數時間複雜度 - 河內塔
    • https://ithelp.ithome.com.tw/upload/images/20190928/20121116UxltrI4GCp.png - 階乘時間複雜度 - 旅行推銷員問題 - NP
      文中提供下面兩張圖,可以很清楚知道效率高低
      https://ithelp.ithome.com.tw/upload/images/20190928/20121116sYARqNKGOT.png
      https://ithelp.ithome.com.tw/upload/images/20190928/20121116pO3oMpQWTa.png

排序算法 - 選擇排序 (Selection sort)、氣泡排序 (Bubble sort)、合併排序 (Merge sort)
搜尋算法 - 二分搜尋 (Binary Search)、循序搜尋 (Sequential Search)

選擇排序 (Selection sort)

def select_sort(origin_items, comp = lambda x, y: x < y):
    items = origin_items[:]
    for i in range (len(items) - 1): 
        min_index = i                
        for j in range(i + 1, len(items)):  
            if comp(items[j], items[min_index]): 
                min_index = j
        items[i], items[min_index] = items[min_index], items[i]  
    return items
origin_items = [1,300,123,44,156,12]
print(select_sort(origin_items))

氣泡排序 (Bubble sort)

def bubble_sort(origin_items, comp = lambda x, y: x > y):
    items = origin_items[:]
    for i in range(len(items) - 1):
        swapped = False
        for j in range(i, len(items) - 1 - i):
            if comp(items[j], items[j + 1]):
                items[j], items[j + 1] = items[j + 1], items[j]
                swapped = True
        if swapped:
            swapped = False
            for j in range (len(items) - 2 - i, i, -1):
                if comp (items[j - 1], items[j]):
                    items[j], items[j - 1] = items[j - 1], items[j]
                    swapped = True
        if not swapped:
            break
    return items
origin_items = [1,300,123,44,156,12]
print(bubble_sort(origin_items))

合併排序 (Merge sort)

def merge_sort(items, comp = lambda x, y: x <= y):
    if len(items) < 2:
        return items[:]
    mid = len(items) // 2
    left = merge_sort(items[:mid], comp)
    right = merge_sort(items[mid:], comp)
    return merge(left, right, comp)

def merge(items1, items2, comp):
    items = []
    index1, index2 = 0, 0
    while index1 < len(items1) and index2 < len(items2):
        if comp(items1[index1], items2[index2]):
            items.append(items1[index1])
            index1 += 1
        else:
            items.append(items2[index2])
            index2 += 1
    items += items1[index1:]
    items += items2[index2:]
    return items
items = [1,300,123,44,156,12]
print(merge_sort(items))

以上三種皆會印出此結果
https://ithelp.ithome.com.tw/upload/images/20190929/20121116BIkDGhH4gS.png
二分搜尋 (Binary Search)

def binary_search(items, key):
    start, end = 0, len(items) - 1
    while start <= end:
        mid = (start + end) // 2
        if key > items[mid]:
            start = mid + 1
        elif key < items[mid]:
            end = mid - 1
        else:
            return mid
    return -1
items = [1,300,123,44,156,12]
print(binary_search(items,100))
print(binary_search(items,123))

循序搜尋 (Sequential Search)

def sequential_search(items, key):
    for index, item in enumerate(items):
        if item == key:
            return index
    return -1
items = [1,300,123,44,156,12]
print(sequential_search(items,100))
print(sequential_search(items,123))

以上兩種皆會印出此結果
https://ithelp.ithome.com.tw/upload/images/20190929/20121116OS4FfErLM8.png
推導式語法 - 可以用來生成列表、集合和字典。

prices = {
    'AAPL': 191.88,
    'GOOG': 1186.96,
    'IBM': 149.24,
    'ORCL': 48.44,
    'ACN': 166.89,
    'FB': 208.09,
    'SYMC': 21.29
}
# 用股票價格 > 100元的股票構成一個新的字典
prices2 = {key: value for key, value in prices.items() if value > 100}
print(prices2)

https://ithelp.ithome.com.tw/upload/images/20190929/20121116YXByBQB93H.png
嵌套的列表

names = ['Andy', 'Alan', 'Amy', 'Adam', 'Alice']
courses = ['國文', '數學', '英文']
# 輸入五個學生三門課的成績
scores = [[None] * len(courses) for _ in range(len(names))]
for row, name in enumerate(names):
    for col, course in enumerate(courses):
        scores[row][col] = float(input(f'請輸入 {name} 的{course}成績: '))
        print(scores)

https://ithelp.ithome.com.tw/upload/images/20190929/20121116FgmhiDylUg.png
heapq、itertools 等的用法
從列表中找出最大的或最小的 N 個元素

import heapq
list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92]
list2 = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
print(heapq.nlargest(3, list1))     # 最大的三個
print(heapq.nsmallest(3, list1))    # 最小的三個
print(heapq.nlargest(2, list2, key = lambda x: x['price']))  # price 最大的兩個
print(heapq.nlargest(2, list2, key = lambda x: x['shares'])) # shares 最大的兩個

https://ithelp.ithome.com.tw/upload/images/20190929/20121116E3N8p5UN9h.png
迭代工具 - 排列 / 组合 / 笛卡兒積

import itertools

# ABCD 的所有排列情況
print(list(itertools.permutations('ABCD')))
# ABCDE 3 個一組的組合
print('----------------------------')
print(list(itertools.combinations('ABCDE', 3)))
# ABCD 和 123 的組合
print('----------------------------')
print(list(itertools.product('ABCD', '123')))

https://ithelp.ithome.com.tw/upload/images/20190929/20121116NMZovcxsgS.png
collections 模組的工具
找出列表中出現次數最多的元素

from collections import Counter
words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around',
    'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes',
    'look', 'into', 'my', 'eyes', "you're", 'under'
]
counter = Counter(words)
print(counter.most_common(3))

https://ithelp.ithome.com.tw/upload/images/20190929/20121116xwwMXqNxB9.png


上一篇
[Day16] 圖像和文檔處理
下一篇
[Day18] Python 語言進階 - 2
系列文
30天學python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言